package com.laihui.activity;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoActivity;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;

import com.laihui.MyApplication;
import com.laihui.adapters.ImagesAdapter;
import com.laihui.base.BaseActivity;
import com.laihui.dialog.Loading;
import com.laihui.entity.DeleteBankCard;
import com.laihui.listener.ImagesAddListener;
import com.laihui.listener.SelectPhotoListener;
import com.laihui.utils.Base64Utils;
import com.laihui.utils.KeyBoardUtil;
import com.laihui.utils.ToastUtil;
import com.laihui.view.NoScrollGridView;
import com.laihui.view.TopBar;
import com.laihui.view.popupwindow.SelectPhotoPopopWindow;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 *
 * https://github.com/crazycodeboy/TakePhoto
 * Created by Administrator on 2018/1/23.
 */

public class UnbingBankCardActivity extends BaseActivity implements TakePhoto.TakeResultListener,InvokeListener {
    private List<String> listUrls = new ArrayList<String>(); //列表中的url
    @BindView(R.id.feedback_grid)
    NoScrollGridView mPicGrid;
    private ImagesAdapter mAdapter;
    private static final int MAX_PICS = 9;

    @BindView(R.id.topbar)
    TopBar topbar;

    @BindView(R.id.btn_next)
    Button btn_next;

    @BindView(R.id.ll_bottom)
    LinearLayout ll_bottom;

    private static final String TAG = TakePhotoActivity.class.getName();
    private TakePhoto takePhoto;
    private InvokeParam invokeParam;
    private MyApplication application;
    private String state;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);

        if (getIntent().getStringExtra("state")!=null){
            state = getIntent().getStringExtra("state");
            if (state.equals("0")){
                ll_bottom.setVisibility(View.VISIBLE);
                btn_next.setEnabled(false);
                btn_next.setBackgroundResource(R.mipmap.button_bg3);
            }
        }

    }
    @Override
    public void init() {
        application = (MyApplication) getApplication();
        topbar.setTitle("上传解绑资料");
        topbar.setOnTopbarClickListener(new TopBar.topbarClickListener() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void rightClick() {

            }
        });
        mAdapter = new ImagesAdapter(this, listUrls, new ImagesAddListener() {

            @Override
            public void add(int position) {
                KeyBoardUtil.hide_keyboard_from(UnbingBankCardActivity.this, mPicGrid);//
                configCompress(takePhoto);
                choosePhoto(MAX_PICS);
            }
        });
        mPicGrid.setAdapter(mAdapter);

    }
    CompressConfig config;
    private void configCompress(TakePhoto takePhoto) {
        config=new CompressConfig.Builder()
                .setMaxSize(1048576)
                .setMaxPixel(1000)
                .enableReserveRaw(false)
                .create();

        takePhoto.onEnableCompress(config,true);
    }


    @OnClick({R.id.btn_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_next:
                if (listUrls.size()==1){
                    ToastUtil.showToast(UnbingBankCardActivity.this,"请上传图片");
                    return;
                }
                Loading.show(this,true);
                Map<String, String> map = new HashMap<>();
                map.put("member_id", application.userId);
                String[] imgall  = new String[listUrls.size()];

                for(int i = 1; i < listUrls.size(); i++) {
                    try {
                        imgall[i] =  Base64Utils.encodeFile(listUrls.get(i));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

                application.apiService.forceunbindBankCard(map,imgall)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<DeleteBankCard>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {
                                Log.e(TAG, "onError: "+e.toString());
                            }


                            public void onNext(DeleteBankCard bankCard) {
                                if (bankCard.getStatus().equals("1")){
                                    ToastUtil.showToast(UnbingBankCardActivity.this,bankCard.getMsg());
                                    Intent intent = new Intent();
                                    setResult(RESULT_OK, intent);
                                    finish();

                                }
                                else {
                                    ToastUtil.showToast(UnbingBankCardActivity.this,bankCard.getMsg());
                                }

                                Loading.dismiss();

                            }
                        });


                break;
        }
    }

    /**
     * 开启图片选择器
     */
    private void choosePhoto(final int limit) {
        new SelectPhotoPopopWindow(this, new SelectPhotoListener() {
            @Override
            public void selectFromAlbum() {
                takePhoto.onPickMultiple(limit);
            }

            @Override
            public void takePhoto() {
                File file=new File(Environment.getExternalStorageDirectory(), "/laihui/"+System.currentTimeMillis() + ".jpg");
                if (!file.getParentFile().exists())file.getParentFile().mkdirs();
                Uri imageUri = Uri.fromFile(file);

            }

                @Override
            public void savePhoto() {

            }
        }, "取消");

    }
    @Override
    public int getLayoutId() {
        return R.layout.unbing_bank_card;
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type=PermissionManager.onRequestPermissionsResult(requestCode,permissions,grantResults);
        PermissionManager.handlePermissionsResult(this,type,invokeParam,this);
    }

    /**
     *  获取TakePhoto实例
     * @return
     */
    public TakePhoto getTakePhoto(){
        if (takePhoto==null){
            takePhoto= (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this,this));
        }
        return takePhoto;
    }

    public void takeSuccess(TResult result) {
        for (int i=0;i<result.getImages().size();i++){
            listUrls.add(result.getImages().get(i).getCompressPath());
        }

        mAdapter.notifyDataSetChanged();

        Log.i(TAG,"takeSuccess：" + result.getImage().getCompressPath());
    }

    public void takeFail(TResult result,String msg) {
        Log.i(TAG, "takeFail:" + msg);
    }

    public void takeCancel() {
        Log.i(TAG, getResources().getString(R.string.msg_operation_canceled));
    }


    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type=PermissionManager.checkPermission(TContextWrap.of(this),invokeParam.getMethod());
        if(PermissionManager.TPermissionType.WAIT.equals(type)){
            this.invokeParam=invokeParam;
        }
        return type;
    }
    @Override
    public Activity bindActivity() {
        return this;
    }
}
